var roleJqGridRowData;
var roledata;
var roledatabak;
$(document).ready(function() {
	$.jgrid.defaults.styleUI = 'Bootstrap';
	// Examle data for jqGrid

	$.ajax({
		type: "get",
		url: YZ.ajaxURLms+"api/jp-BIRM-UserProfile-ms/roles/",
		//			data: JSON.stringify(datajson),
		dataType: "json",
		async: false,
		//ContentType: "application/json;charset=UTF-8",
		//contentType: "application/json",
		//			<!-- //crossDomain:true, -->
		//			headers:{
		//				"Content-Type":"application/json;charset=UTF-8"
		//			},
		success: function(data) {
			roledata = data;
			roledatabak = data;
		}
	});

	// Configuration for jqGrid Example 1

	$("#table_list_1").jqGrid({
		data: roledata,
		datatype: "local",
		height: 530,
		autowidth: true,
		shrinkToFit: true,
		rowNum: 14,
		rowList: [10, 20, 30],
		rownumbers: true,
		colNames: ['序号', '角色名称', '等级', '等级排列', '备注'],
		colModel: [{
				name: 'id',
				index: 'id',
				hidden: true
			},

			{
				name: 'name',
				index: 'name',
				width: 100
			},
			{
				name: 'stageCode',
				index: 'stageCode',
				width: 80,
				align: "left",
			},

			{
				name: 'privilegeCode',
				index: 'privilegeCode',
				width: 50,
			},

			{
				name: 'remark',
				index: 'remark',
				width: 120,
			}

		],
		pager: "#pager_list_1",
		viewrecords: true,
		caption: "",
		hidegrid: false,
		onSelectRow: function(rowId, status) {
			roleJqGridRowData = $("#table_list_1").jqGrid("getRowData", rowId);
		}
	});

	//			 $("#table_list_1").setSelection(1, true);

	// Add responsive to jqGrid
	$(window).bind('resize', function() {
		var width = $('.jqGrid_wrapper').width();
		$('#table_list_1').setGridWidth(width);

	});

	/* $("#add-btn").click(function(){
              	
            	$(".modal-title").html("新增警员信息");
            	
            })
           
            $("#update-btn").click(function(){
            	//显示弹窗
            	$(this).attr("data-target","#myModal");
            	$(".modal-title").html("修改警员信息")
            });
            
            $("#delete-btn").click(function(){
            	layer.confirm('是否确定要删除？', {
					  btn: ['是的','取消'] //按钮
					}, function(){
					  layer.msg('删除成功', {icon: 1});
					});
            })*/

	$("#update-btn").click(function() {
		$(".modal-title").html("修改角色信息");
		if(roleJqGridRowData == null || roleJqGridRowData == '') {
			layer.confirm('请指定修改的信息列！', {
				btn: ['是的'] //按钮
			});
			$(this).attr("data-target", "");
		} else {
			$(this).attr("data-target", "#myModal");
			//数据回显过程
			//console.log(roleJqGridRowData.name);
			$("#cname").val(roleJqGridRowData.name);
			var stage =roleJqGridRowData.stageCode;
			$("#stageCode").find("option[value = '"+stage+"']").attr("selected","selected");
			//          		$("#").val(roleJqGridRowData.invdate);
			$("#privilegeCode").val(roleJqGridRowData.privilegeCode);
			$("#remark").val(roleJqGridRowData.remark);
		}
	});

	$("#jssq-btn").click(function() {
		if(roleJqGridRowData == null || roleJqGridRowData == '') {
			layer.confirm('请指定要授权的角色！', {
				btn: ['是的'] //按钮
			});
			$(this).attr("data-target", "");
		} else {
			$(this).attr("data-target", "#myModal1");
		}
	});

	$("#jcsq-btn").click(function() {
		if(roleJqGridRowData == null || roleJqGridRowData == '') {
			layer.confirm('请指定要解除授权的角色！', {
				btn: ['是的'] //按钮
			});
			$(this).attr("data-target", "");
		} else {
			$(this).attr("data-target", "#myModal2");
			var setting2 = {
				check: {
					enable: true
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onCheck: zTreeOnCheck2
				},
				view: {
					selectedMulti: true
				}
			};
			var setting3 = {
				check: {
					enable: true
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					onCheck: zTreeOnCheck3
				},
				view: {
					selectedMulti: true
				}
			};

			function removeByValue(arr, val) {
				for(var i = 0; i < arr.length; i++) {
					if(arr[i] == val) {
						arr.splice(i, 1);
						break;
					}
				}
			}

			var jcusersmenus = [];
			var jcusersqxyzs = [];

			function zTreeOnCheck2(event, treeId, treeNode) {
				if(treeNode.checked == true) {
					jcusersmenus.push(treeNode.id);
				} else {
					removeByValue(jcusersmenus, treeNode.id);
				}
				//										
				//						treeNode.check
				//var checked = treeNode.checked;  
				//						console.log((treeNode?treeNode.name:"root") + "checked " +(checked?"true":"false"));  
				//						refreshLayers();
				//						clearCheckedOldNodes();
				//								console.log(jcusersmenus);
			};

			function zTreeOnCheck3(event, treeId, treeNode) {
				if(treeNode.checked == true) {
					jcusersqxyzs.push(treeNode.id);
				} else {
					removeByValue(jcusersqxyzs, treeNode.id);
				}
				//						console.log(usersqxyzs);
				//						treeNode.check
				//var checked = treeNode.checked;  
				//						console.log((treeNode?treeNode.name:"root") + "checked " +(checked?"true":"false"));  
				//						refreshLayers();
				//						clearCheckedOldNodes();
				//				console.log(jcusersqxyzs);
			};

			var zNodes2 = [];
			var zNodes3 = [];
			$.ajax({
				type: "get",
				url: YZ.ajaxURLms+"api/jp-BIRM-UserProfile-ms/roles/" + roleJqGridRowData.id,
				async: false,
				success: function(data) {
					if(data["privilegeFunctions"].length > 0) {
						for(var i = 0; i < data["privilegeFunctions"].length; i++) {
							var o = new Object();
							o.id = data["privilegeFunctions"][i]["id"];
							o.name = data["privilegeFunctions"][i]["name"];
							if(data["privilegeFunctions"][i]["parentPrivilegeFunction"] == null) {
								o.pId = "";
							} else {
								o.pId = data["privilegeFunctions"][i]["parentPrivilegeFunction"]["id"];
							}
							zNodes2.push(o);
						}
					} else {
						//						layer.confirm('该角色下没有菜单！', {
						//							btn: ['是的'] //按钮
						//						});
						//						$(".next").click();
					}
				}
			});

			$.ajax({
				type: "get",
				url: YZ.ajaxURLms+"api/jp-BIRM-UserProfile-ms/roles/" + roleJqGridRowData.id,
				async: false,
				success: function(data) {
					if(data["privilegeActions"].length > 0) {
						for(var i = 0; i < data["privilegeActions"].length; i++) {
							var o = new Object();
							o.id = data["privilegeActions"][i]["id"];
							o.name = data["privilegeActions"][i]["name"];
							if(data["privilegeActions"][i]["parentPrivilegeFunction"] == null) {
								o.pId = "";
							} else {
								o.pId = data["privilegeActions"][i]["parentPrivilegeFunction"]["id"];
							}
							zNodes3.push(o);
						}
					} else {
						//						layer.confirm('该角色下没有权限因子！', {
						//							btn: ['是的'] //按钮
						//						});
						//						if(data["privilegeFunctions"].length > 0){
						//							$(".prev").click();
						//						}else{
						//							$(".close").click();
						//						}
					}

				}
			});

			var code1;

			function setCheck1() {
				var zTree2 = $.fn.zTree.getZTreeObj("treeDemo2"),
					py = $("#py").attr("checked") ? "p" : "",
					sy = $("#sy").attr("checked") ? "s" : "",
					pn = $("#pn").attr("checked") ? "p" : "",
					sn = $("#sn").attr("checked") ? "s" : "",
					type = {
						"Y": py + sy,
						"N": pn + sn
					};
				zTree2.setting.check.chkboxType = type;
				var zTree3 = $.fn.zTree.getZTreeObj("treeDemo3"),
					py = $("#py").attr("checked") ? "p" : "",
					sy = $("#sy").attr("checked") ? "s" : "",
					pn = $("#pn").attr("checked") ? "p" : "",
					sn = $("#sn").attr("checked") ? "s" : "",
					type = {
						"Y": py + sy,
						"N": pn + sn
					};

				zTree3.setting.check.chkboxType = type;
				showCode('setting.check.chkboxType = { "Y" : "' + type.Y + '", "N" : "' + type.N + '" };');
			}

			//			function showCode(str) {
			//				if(!code) code = $("#code");
			//				code.empty();
			//				code.append("<li>" + str + "</li>");
			//			}

			$("#rolebtfinish1").click(function() {
				var usersmenus = [];
				var usersqxyzs = [];
				var a = $.fn.zTree.getZTreeObj("treeDemo2").getCheckedNodes();
				var b = $.fn.zTree.getZTreeObj("treeDemo3").getCheckedNodes();
				if(a.length == 0 && b.length == 0) {
					layer.confirm('没有选择权限，操作无效！', {
						btn: ['是的'] //按钮
					});
					$(".close").click();
				} else {
					//						console.log(usersmenus);
					//console.log(usersqxyzs);
					//						console.log(roleJqGridRowData.id);
					for(var i = a.length - 1; i > -1; i--) {
								usersmenus.push(a[i].id)
							}

							for(var i = b.length - 1; i > -1; i--) {
								usersqxyzs.push(b[i].id)
							}
					$.ajax({
						type: "PUT",
						url: YZ.ajaxURLms+"api/jp-BIRM-UserProfile-ms/roles/revokeRolePrivilege/" + roleJqGridRowData.id + "?functionIds=" + jcusersmenus + "&actionIds=" + jcusersqxyzs,
						//								data: {"functionIds":usersmenus,"actionIds":usersqxyzs},
						//			data: JSON.stringify(datajson),
						dataType: "json",
						async: false,
						ContentType: "application/json;charset=UTF-8",
						contentType: "application/json",
						headers: {
							"Content-Type": "application/json;charset=UTF-8"
						},
						success: function() {
							$("#rolebtngb").click();
							layer.msg('解除成功', {
								icon: 1
							});
							setTimeout(function() {
								location.reload();
							}, 1000);
						}
					});
					$(".close").click();
				}
			});

			$.fn.zTree.init($("#treeDemo2"), setting2, zNodes2);
			$.fn.zTree.init($("#treeDemo3"), setting3, zNodes3);
			setCheck();
			$("#py").bind("change", setCheck);
			$("#sy").bind("change", setCheck);
			$("#pn").bind("change", setCheck);
			$("#sn").bind("change", setCheck);
		}
	});

	$("#delete-btn").click(function() {
		if(roleJqGridRowData == null || roleJqGridRowData == '') {
			layer.confirm('请指定删除的信息列！', {
				btn: ['是的'] //按钮
			});
			//$(this).attr("data-target","");
		} else {
			layer.confirm('是否确定要删除？', {
				btn: ['是的', '取消'] //按钮
			}, function() {
				//						调用ajax删除接口 
				var roleid = roleJqGridRowData.id;
				$.ajax({
					type: "DELETE",
					url: YZ.ajaxURLms+"api/jp-BIRM-UserProfile-ms/roles/" + roleid,
					//			data: JSON.stringify(datajson),
					//					dataType: "json",
					dataType: "text",
					async: false,
					ContentType: "application/json;charset=UTF-8",
					contentType: "application/json",
					headers: {
						"Content-Type": "application/json;charset=UTF-8"
					},
					success: function() {
						layer.msg('删除成功', {
							icon: 1
						});
						setTimeout(function() {
							location.reload()
						}, 1000);
					},
					error: function() {
						layer.confirm('删除失败！', {
							btn: ['是的'] //按钮
						});
					}
				});
			});
		}
	});
	$("#add-btn").click(function() {
		$(".modal-title").html("新增角色信息");
		//显示弹窗
		$("#cname").val("");
		$("#privilegeCode").val("");
		$("#remark").val("");
		$(this).attr("data-target", "#myModal");
	});

	$("#rolebtnss").click(function() {
	
		if($("#roletextss").val() == "") {
			$("#table_list_1").jqGrid('clearGridData');
			$("#table_list_1").jqGrid('setGridParam', {
				data: roledatabak
			}).trigger("reloadGrid");
		} else {
			var namelike = $("#roletextss").val();
			//ajax调接口，给roledata赋值
			$.ajax({
				type: "get",
				url: YZ.ajaxURLms+"api/jp-BIRM-UserProfile-ms//roles/?nameLike=" + namelike,
				//			data: JSON.stringify(datajson),
				dataType: "json",
				async: false,
				//ContentType: "application/json;charset=UTF-8",
				//contentType: "application/json",
				//			<!-- //crossDomain:true, -->
				//			headers:{
				//				"Content-Type":"application/json;charset=UTF-8"
				//			},
				success: function(result) {
					console.log(result);
					roledata = result;
				}

			});
			$("#table_list_1").jqGrid('clearGridData');
			$("#table_list_1").jqGrid('setGridParam', {
				data: roledata
			}).trigger("reloadGrid");
		}
	});

});